package com.idea.relax.tool.core.tree;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author azhao
 */
public class TreeVisit<T> extends ListTree<T> {
    private Logger logger = LoggerFactory.getLogger(TreeVisit.class);

    public void visitTree(List<T> source, Consumer<T> consumer) {
        if (check(source)) {
            logger.info("检查失败");
            return;
        }
        init(source);
        try {
            for (T t : source) {
                T obj = cloneObject(t);
                id.set(obj, id.get(t));
                if (level != null) {
                    level.set(obj, 1);
                }
                T at = cloneObject(t);
                children.set(at, new ArrayList<>());
                consumer.accept(at);
                traverseTreeToList(t, levelNumber, consumer);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取父节点列表
     *
     * @param t
     * @param list 树 list
     * @return
     */
    public List<T> getParentsList(T t, List<T> list) {
        List<T> result = new ArrayList<>();
        try {
            for (T t1 : list) {
                //todo
            }
            while (true) {
                T o = (T) parentId.get(t);
                if (o == null) {
                    break;
                }
                list.add(o);
                t = o;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void traverseTreeToList(T obj, int levelNumber, Consumer<T> consumer) throws IllegalAccessException {
        List<T> childrenList = (List<T>) children.get(obj);
        ++levelNumber;
        if (childrenList != null && !childrenList.isEmpty()) {
            for (T t : childrenList) {
                parentId.set(t, id.get(obj));
                if (level != null) {
                    level.set(t, levelNumber);
                }
                T at = cloneObject(t);
                children.set(at, new ArrayList<>());
                consumer.accept(at);
                traverseTreeToList(t, levelNumber, consumer);
            }
        }
    }
}
